package com.alog.javaee.day39;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Auther: Ye Zhengdong
 * @Date: 2019/2/19 18:59
 * @Description:
 */
@WebServlet("/cookieServlet")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = req.getCookies();
        boolean flag = false ;
        if(cookies != null && cookies.length > 0){
            for(Cookie cookie : cookies){
                String name = cookie.getName();
                if("lastTime".equals(name)){
                    flag = true;
                    String value = cookie.getValue();
                    value = URLDecoder.decode(value,"UTF-8");

                    DateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String format1 = format.format(new Date());
                    format1 = URLEncoder.encode(format1, "UTF-8");
                    cookie.setValue(format1);
                    cookie.setMaxAge(30 * 24 * 60 * 60);
                    resp.addCookie(cookie);

                    resp.getWriter().write("欢迎回来, 您上次的登陆时间为:" + value);
                    break;
                }
            }
        }

        if(!flag){
            DateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String format1 = format.format(new Date());
            format1 = URLEncoder.encode(format1, "UTF-8");
            Cookie cookie = new Cookie("lastTime", format1);
            cookie.setValue(format1);
            cookie.setMaxAge(30 * 24 * 60 * 60);
            resp.addCookie(cookie);

            resp.getWriter().write("您好, 欢迎首次访问");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
